//
//  FaBiPurchaseViewController.m
//  Exchange
//
//  Created by 张庆勇 on 2018/7/25.
//  Copyright © 2018年 张庆勇. All rights reserved.
//

#import "FaBiPurchaseViewController.h"
#import "WaitForPaymentOrederViewController.h"
#import "LoginViewController.h"
#import "CheckVersionAlearView.h"
#import "IdentityAuthenticationViewController.h"
#import "BindBankViewController.h"
#import "BankWithSetViewController.h"
@interface FaBiPurchaseViewController ()<UITextFieldDelegate>
@property (nonatomic,strong)NSString *asset; //买入币种
@property (nonatomic,strong)NSString *buy_price;//买入估价
@property (nonatomic,strong)NSString *min_amount;//最小交易额
@property (nonatomic,strong)NSMutableArray *dataArray;
@end

@implementation FaBiPurchaseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(LoginSusess) name:LoginSusessNotificationse object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getBankData:) name:bindbnakNotificationse object:nil];
    [self initUI];
    [self getBank];
    // 上拉加载
    WeakSelf
    WLRefreshGifHeader *header = [WLRefreshGifHeader headerWithRefreshingBlock:^{
        
        [weakSelf getData];
        
    }];
    [header beginRefreshing];
    self.tableview.mj_header = header;
}
- (void)getBankData:(NSNotification *)message
{
   [self getBank];
}
- (void)LoginSusess
{
    [self getBank];
    [self getUserInfo];
}
- (void)getBank
{
    if ([EXUserManager isLogin]) {
        _buybutton.userInteractionEnabled = NO;
        WeakSelf
        [HomeViewModel getUserbankWithDic:@{} url:userbank callBack:^(BOOL isSuccess, id callBack) {
            if (isSuccess) {
                weakSelf.dataArray = callBack;
                weakSelf.buybutton.userInteractionEnabled = YES;
            }
        }];

    }
}
- (void)getUserInfo
{
    [HomeViewModel getUserWithDic:@{} url:getUser callBack:^(BOOL isSuccess, id callBack) {
        if (!isSuccess) {
            [self axcBasePopUpWarningAlertViewWithMessage:callBack[@"message"] view:kWindow];
        }
    }];
}
- (void)getData
{
    WeakSelf
    [HomeViewModel getC2CPriceInfoWithDic:@{} url:c2cPrice callBack:^(BOOL isSuccess, id callBack) {
        if (isSuccess)
        {
            weakSelf.assetlable.text = callBack[@"result"][@"asset"];
            weakSelf.buy_price = callBack[@"result"][@"buy_price"];
            weakSelf.min_amount = callBack[@"result"][@"min_amount"];
            weakSelf.CNY_Price.text = [NSString stringWithFormat:@"%.2f",weakSelf.buy_price.floatValue];
            
            weakSelf.priceField.placeholder = [NSString stringWithFormat:@"%@%@",Localized(@"C2C_Minimum_volume"),weakSelf.min_amount];
            [weakSelf.priceField setValue:[ZBLocalized sharedInstance].C2CTextPColor forKeyPath:@"_placeholderLabel.textColor"];
            [weakSelf.priceField setValue:AutoFont(18) forKeyPath:@"_placeholderLabel.font"];
            weakSelf.priceField.tintColor = TABTITLECOLOR;
            
            [weakSelf.buybutton setTitle:[NSString stringWithFormat:@"%@ CNY —> %@",Localized(@"C2C_CL_Buy"),weakSelf.assetlable.text] forState:0];
        }
        [weakSelf.tableview.mj_header endRefreshing];
    }];
}
- (void)setUIwithSet:(UILabel *)Lable text:(NSString *)text font:(UIFont *)font textColor:(UIColor *)textColor
{
    Lable.textColor = textColor;
    Lable.font = font;
    if (Lable ==self.tipsContontLable)
    {
         Lable.attributedText = [EXUnit finderattributedString:text attributedString:Localized(@"C2C_message_world") color:MAINTITLECOLOR font:AutoBoldFont(11)];
    }else
    {
       Lable.text = text;
    }
}
- (void)initUI
{
    self.tableview.backgroundColor = MAINBLACKCOLOR;
    self.tableview.showsVerticalScrollIndicator = NO;
    self.bgView.backgroundColor = MAINBLACKCOLOR;
    self.bgView2.backgroundColor = MAINBLACKCOLOR;
    self.headView.backgroundColor = [ZBLocalized sharedInstance].BgViewLightColor;
    [self setUIwithSet:self.titleLable1 text:Localized(@"C2C_Buy_estimate") font:AutoBoldFont(12) textColor:[ZBLocalized sharedInstance].C2CTitleTextColor];
    [self setUIwithSet:self.CNY_Price text:@"" font:AutoBoldFont(21) textColor:MAINTITLECOLOR];
    [self setUIwithSet:self.rightLable text:@"CNY" font:AutoBoldFont(12) textColor:MAINTITLECOLOR1];
    self.line1.backgroundColor =CELLCOLOR;
    //
    [self setUIwithSet:self.titleLable2 text:Localized(@"C2C_Buy_volume") font:AutoBoldFont(12) textColor:[ZBLocalized sharedInstance].C2CTitleTextColor];
    
    self.CNT_numberField.placeholder = Localized(@"C2C_purchase_quantity");
    [self.CNT_numberField setValue:[ZBLocalized sharedInstance].C2CTextPColor forKeyPath:@"_placeholderLabel.textColor"];
    [self.CNT_numberField setValue:AutoFont(18) forKeyPath:@"_placeholderLabel.font"];
    self.CNT_numberField.tintColor = TABTITLECOLOR;
    self.CNT_numberField.textColor = MAINTITLECOLOR;
    [self.CNT_numberField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    [self setUIwithSet:self.assetlable text:[AppDelegate shareAppdelegate].DICKEY font:AutoBoldFont(12) textColor:MAINTITLECOLOR1];
     self.line2.backgroundColor =CELLCOLOR;
    
    //
    [self setUIwithSet:self.titleLable3 text:Localized(@"C2C_money") font:AutoBoldFont(12) textColor:[ZBLocalized sharedInstance].C2CTitleTextColor];
    
    self.priceField.placeholder = Localized(@"C2C_Minimum_volume");
    [self.priceField setValue:[ZBLocalized sharedInstance].C2CTextPColor forKeyPath:@"_placeholderLabel.textColor"];
    [self.priceField setValue:AutoFont(18) forKeyPath:@"_placeholderLabel.font"];
    self.priceField.tintColor = TABTITLECOLOR;
    self.priceField.textColor = MAINTITLECOLOR;
    self.priceField.delegate = self;
    self.line3.backgroundColor =CELLCOLOR;
    [self setUIwithSet:self.rightLable1 text:@"CNY" font:AutoBoldFont(12) textColor:MAINTITLECOLOR1];
    
  //
    [self setUIwithSet:self.titleLable4 text:Localized(@"C2C_Payment_method") font:AutoBoldFont(12) textColor:[ZBLocalized sharedInstance].C2CTitleTextColor];
    [self setUIwithSet:self.bankLable text:Localized(@"C2C_Bank_card") font:AutoBoldFont(21) textColor:MAINTITLECOLOR];
//
    _buybutton.backgroundColor = TABTITLECOLOR;
    _buybutton.titleLabel.font = AutoBoldFont(15);
 
    KViewRadius(_buybutton, 2);
     [self.buybutton setTitle:[NSString stringWithFormat:@"%@ CNY —> %@",Localized(@"C2C_CL_Buy"),self.assetlable.text] forState:0];
    //
    
    [self setUIwithSet:self.messageLable text:Localized(@"C2C_merchants_message") font:AutoFont(12) textColor:MAINTITLECOLOR1];
    [self setUIwithSet:self.tipsLable text:Localized(@"C2C_Reminder") font:AutoFont(11) textColor:TABTITLECOLOR];
    [self setUIwithSet:self.tipsContontLable text:Localized(@"C2C_message") font:AutoFont(11) textColor:MAINTITLECOLOR1];
  
}
- (void)viewWillLayoutSubviews
{
    
    _bgView1.height = self.tipsContontLable.height +50;
    _bgView1.width = UIScreenWidth -RealValue_W(60);
    _bgView1.backgroundColor = [ZBLocalized sharedInstance].C2CboxBgColor;
    _bgView1.layer.mask = [EXUnit ShapeLayerWithViewCGRect:_bgView1 cornerRadius:4];
    _headView.height = _bgView1.height + 900;
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if (textField == _priceField) {
        return NO;
    }else
    {
        return YES;
    }
}
- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)textFieldDidChange:(UITextField *)TextField{
    
    if (TextField.text.length ==0 ||[NSString isEmptyString:TextField.text])
    {
        _priceField.text = @"";
    }else
    {
        _priceField.text =  [NSString stringWithFormat:@"%.2f",TextField.text.floatValue * self.buy_price.floatValue];
    }
    
    
}
- (IBAction)buyButton:(LcButton *)sender {
    if (![EXUserManager isLogin])
    {
        [self SetThePassword];
        [sender stopAnimation];
        return;
    }
    
    WeakSelf
    if ([AppDelegate shareAppdelegate].isBecomeActive) {
        
        if ([EXUnit isOpenTouchid] && ![EXUnit isOpenGesture]) {
            [sender stopAnimation];
            [YWFingerprintVerification fingerprintVerificationCallBack:^(NSError *error) {
                if(!error){
                    //验证成功，主线程处理UI
                    dispatch_async(dispatch_get_global_queue(0, 0), ^{
                        // 处理耗时操作的代码块...
                        
                        //通知主线程刷新
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [weakSelf Buy:sender];
                        });
                        
                    });
                }else{
                    //验证成功，主线程处理UI
                    dispatch_async(dispatch_get_global_queue(0, 0), ^{
                        // 处理耗时操作的代码块...
                        
                        //通知主线程刷新
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [EXUserManager removeUserInfo];
                            [weakSelf SetThePassword];
                        });
                        
                    });
                    
                }
            }];
        }else if (![EXUnit isOpenTouchid] && [EXUnit isOpenGesture])
        {
            [sender stopAnimation];
            //验证手势密码
            [YWUnlockView showUnlockViewWithType:YWUnlockViewUnlock callBack:^(BOOL result) {
                if (result) {
                    [weakSelf Buy:sender];
                }else
                {
                    [EXUserManager removeUserInfo];
                    [weakSelf SetThePassword];
                }
                
                
            }];
            
        }else if (![EXUnit isOpenTouchid] && ![EXUnit isOpenGesture])
        {
            [weakSelf Buy:sender];
        }
    }else
    {
        [weakSelf Buy:sender];
    }
    
    
    
}
- (void)SetThePassword
{
    LoginViewController * loginView = [[LoginViewController alloc] init];
    [[EXUnit currentViewController] presentViewController:loginView animated:YES completion:nil];
}
- (void)Buy:(LcButton *)sender
{
   
    
    [AppDelegate shareAppdelegate].isBecomeActive = NO;
    if ([EXUserManager RealName].integerValue ==0) { //未认证
        [self popRealName:YES title:Localized(@"transaction_authenticated_title") message:Localized(@"transaction_authenticated_message")];
        [sender stopAnimation];
        
    }else if ([EXUserManager RealName].integerValue ==1 ||[EXUserManager RealName].integerValue ==4)//审核中
    {
         [EXUnit showMessage:Localized(@"C2C_under_review")];
        [sender stopAnimation];
        
        
    }else if ([EXUserManager RealName].integerValue ==3)//认证失败
    {
        
        [self popRealName:YES title:Localized(@"transaction_authenticated_title") message:Localized(@"transaction_authenticated_failed")];
        [sender stopAnimation];
        
        
    }else if ([EXUserManager RealName].integerValue ==2)//认证成功
    {
        if (self.dataArray.count==0)
        {
            
            [self popRealName:NO title:Localized(@"C2C_bank_card") message:Localized(@"C2C_bank_card_message")];
            [sender stopAnimation];
        }else
        {
            [sender stopAnimation];
            
            if ([[EXUnit getSite] isEqualToString:@"KCoin"])
            {
                if (![EXUnit KCionC2C500WithPrice:self.priceField.text])
                {
                   [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"C2CBuyMessage") view:kWindow];
                }
            }else
            {
                if (_priceField.text.floatValue < _min_amount.floatValue) {
                    [self axcBasePopUpWarningAlertViewWithMessage:[NSString stringWithFormat:Localized(@"C2C_Minimum_purchase"),_min_amount,self.assetlable.text] view:kWindow];
                    
                    return;
                }
            }
            
            
            BankWithSetViewController * Choosebank = [[BankWithSetViewController alloc] init];
            Choosebank.ischooseBank = YES;
            Choosebank.title = Localized(@"C2C_Choose_bank_card");
            [self.navigationController pushViewController:Choosebank animated:YES];
            WeakSelf
            Choosebank.addBankblock = ^(BankModle *modle) {
                
                [self POSTWithHost:@"" path:c2ctrade param:@{@"amount":weakSelf.priceField.text,@"type":@"1",@"user_bank_id":modle.ID} cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                    [sender stopAnimation];
                    if ([responseObject[@"code"] integerValue]==0)//成功
                    {
                        
                        WOrderModle * modle = [WOrderModle mj_objectWithKeyValues:responseObject[@"result"][@"order"]];
                        WaitForPaymentOrederViewController *WOrderInfoVC = [[WaitForPaymentOrederViewController alloc] init];
                        WOrderInfoVC.modle = modle;
                        WOrderInfoVC.dic = responseObject[@"result"][@"merchant"];
                        [self.navigationController pushViewController:WOrderInfoVC animated:YES];
                        weakSelf.priceField.text = @"";
                        weakSelf.CNT_numberField.text = @"";
                        
                    }else
                    {
                        [self axcBasePopUpWarningAlertViewWithMessage:responseObject[@"message"] view:kWindow];
                    }
                    
                } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    [sender stopAnimation];
                }];
                
            };
            
        }
    }
    
}
- (void)popRealName:(BOOL)isRealName title:(NSString *)title message:(NSString *)message
{
    if (isRealName) {
        CheckVersionAlearView * aleartVC = [[CheckVersionAlearView alloc] initWithmessage:message
                                                                                 titleStr:title
                                                                                  openUrl:@""
                                                                                  confirm:Localized(@"transaction_OK")
                                                                                   cancel:Localized(@"transaction_cancel")
                                                                                    state:2
                                                                            RechargeBlock:^
                                            {
                                                
                                                IdentityAuthenticationViewController * idACationVC = [[IdentityAuthenticationViewController alloc] init];
                                                idACationVC.title = Localized(@"my_identity_authentication");
                                                [[EXUnit currentViewController].navigationController pushViewController:idACationVC animated:YES];
                                                
                                                
                                            }];
        aleartVC.animationStyle = LXASAnimationTopShake;
        [aleartVC showLXAlertView];
    }else
    {
        CheckVersionAlearView * aleartVC = [[CheckVersionAlearView alloc] initWithmessage:message
                                                                                 titleStr:title
                                                                                  openUrl:@""
                                                                                  confirm:Localized(@"transaction_OK")
                                                                                   cancel:Localized(@"transaction_cancel")
                                                                                    state:2
                                                                            RechargeBlock:^{
                                                                                
                                                                                BindBankViewController * bindbank = [[BindBankViewController alloc] init];
                                                                                bindbank.title = Localized(@"my_Bank_card_settings");
                                                                                [self.navigationController pushViewController:bindbank animated:YES];
                                                                                
                                                                            }];
        aleartVC.animationStyle = LXASAnimationTopShake;
        [aleartVC showLXAlertView];
    }
}
- (IBAction)ChooseButton:(UIButton *)sender {
    
    
}
@end
